

import { useEffect, useRef, useState } from 'react';
import { 
  StyleSheet, 
  View, 
  Text,
  TouchableOpacity,
  Image,
  SectionList,
  LayoutAnimation,
  Alert,
  Switch,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import PageTitle from '../components/PageTitle';
import AddCount from '../components/AddCount';
import AddIcon from '../assets/icon_add.png';
import { getStorage, setStorage } from '../utils/storage';
import icon_game from '../assets/icon_game.png';
import icon_bank from '../assets/icon_bank.png';
import icon_platform from '../assets/icon_platform.png';
import icon_other from '../assets/icon_other.png';
import icon_arrow from '../assets/icon_arrow.png';
const typeIcon = {
  '游戏': icon_game,
  '平台': icon_platform,
  '银行卡': icon_bank,
  '其他': icon_other,
}
const types = ['游戏', '平台', '银行卡', '其他'];


const Home = () => {
  const insets = useSafeAreaInsets();
  const [list, setList] = useState<any>([]);
  const [sectionState, setSectionState] = useState({
    '游戏': true,
    '平台': true,
    '银行卡': true,
    '其他': true,
  })
  const [showPwd, setShowPwd] = useState(true);
  const addCountRef = useRef(null);
  useEffect(() => {
    getList()
  }, [])

  const getList = async () => {
    const res = await getStorage('countList');
    if (res && res.length) {
      const sectionList = types.map((item) => {
        return {
          type: item,
          data: res.filter((i: any) => i.type === item) || []
        }
      })
      // 使用spring动画
      LayoutAnimation.configureNext({
        duration: 500,
        create: {
          type: LayoutAnimation.Types.spring,
          property: LayoutAnimation.Properties.scaleXY,
          springDamping: 0.7,
          initialVelocity: 0
        },
        update: {
          type: LayoutAnimation.Types.spring,
          springDamping: 0.7
        }
      });
      setList(sectionList);
    }
  }
  const openModal = () => {
    addCountRef.current?.show();
  }
  const renderItem = ({ item, index, section }: any) => {
    if (!sectionState[section.type]) return null
    const styles = StyleSheet.create({
      itemWrapper: {
        width: '100%',
        flexDirection: 'column',
        padding: 12,
        backgroundColor: '#fff',
        borderTopWidth: 0.5,
        borderTopColor: '#e0e0e0',
      },
      nameTxt: {
        fontSize: 16,
        fontWeight: '500',
        color: '#333',
      },
      accpwdWrap: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 12,
        // marginBottom: 6,
      },
      accpwdTxt: {
        flex: 1,
        fontSize: 14,
        color: '#666',
      }
    })
    return (
      <TouchableOpacity 
        style={styles.itemWrapper}
        activeOpacity={0.7}
        onPress={() => {
          addCountRef.current?.show(item);
        }}
        onLongPress={() => {
          Alert.alert('提示', `确定删除${item.name}账号吗？`, [
            {
              text: '取消',
              onPress: () => {},
              style: 'cancel'
            },
            {
              text: '确定',
              onPress: async () => {
                const res = await getStorage('countList');
                if (res && res.length) {
                  const newList = res.filter((i: any) => i.id !== item.id);
                  await setStorage('countList', newList);
                  getList();
                }
              }
            }
          ])
        }}
        >
        <Text style={styles.nameTxt}>{item.name}</Text>
        <View style={styles.accpwdWrap}>
          <Text style={styles.accpwdTxt}>账号：{item.count}</Text>
          <Text style={styles.accpwdTxt}>密码：{showPwd ? item.password : '******'}</Text>
        </View>
      </TouchableOpacity>
    )
  }
  const renderSectionHeader = ({ section }: { section: { type: string, data: any[] } }) => {
    const { type } = section
    const styles = StyleSheet.create({
      sectionHeader: {
        flexDirection: 'row',
        alignItems: 'center',
        height: 46,
        backgroundColor: '#fff',
        borderTopLeftRadius: 12,
        borderTopRightRadius: 12,
        paddingHorizontal: 12,
        marginTop: 12,
      },
      sectionHeaderRadius: {
        borderRadius: 12,
      },
      typeIcon: {
        width: 24,
        height: 24,
        resizeMode: 'contain',
      },
      typeTxt: {
        marginLeft: 16,
        fontSize: 16,
        fontWeight: '500',
        color: '#333',
      },
      arrowBtn: {
        // borderColor: 'red',
        // borderWidth: 1,
        marginLeft: 'auto', 
      },
      arrow: {
        width: 20,
        height: 20,
        resizeMode: 'contain',
      }
    })
    return (
      <View 
        style={[
          styles.sectionHeader,
          (!sectionState[type] || !section.data.length) && styles.sectionHeaderRadius
          ]}
        >
        <Image style={styles.typeIcon} source={typeIcon[type]} />
        <Text style={styles.typeTxt}>{type}</Text>
        <TouchableOpacity 
          style={styles.arrowBtn}
          activeOpacity={0.7}
          onPress={() => {
            const copy = {...sectionState}
            copy[type] = !copy[type]
            // 使用spring动画
            LayoutAnimation.configureNext({
              duration: 500,
              create: {
                type: LayoutAnimation.Types.spring,
                property: LayoutAnimation.Properties.scaleXY,
                springDamping: 0.7,
                initialVelocity: 0
              },
              update: {
                type: LayoutAnimation.Types.spring,
                springDamping: 0.7
              }
            });
            setSectionState(copy);
          }}
        >
          <Image 
            style={[
              styles.arrow, 
              {
                transform: [
                  { rotate: sectionState[type] ? '0deg' : '-90deg' }
                ],
              }
            ]}
            source={icon_arrow} 
          />
        </TouchableOpacity>
        
      </View>
    )
  }
  return (
    <View 
      style={
        [
          styles.root,
          {
            // paddingTop: insets.top,
            marginTop: insets.top,
            paddingBottom: insets.bottom,
          }
        ]}
      >
      <PageTitle title="账号管理">
        <Switch 
          style={styles.switch}
          value={showPwd}
          onValueChange={setShowPwd}
        />
      </PageTitle>
      <SectionList
        sections={list}
        keyExtractor={item => item.id}
        renderItem={renderItem}
        renderSectionHeader={renderSectionHeader}
        contentContainerStyle={styles.listContainer}
      />
      <AddCount 
        ref={addCountRef} 
        types={types}
        onSave={getList}
      />
      <TouchableOpacity 
        style={styles.addBtn}
        activeOpacity={0.7}
        onPress={openModal}
      >
        <Image source={AddIcon} style={styles.addIcon} />
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  root: {
    flex: 1,
    backgroundColor: '#f5f5f5',
    // borderColor: 'red',
    // borderWidth: 1,
  },
  switch: {
    position: 'absolute',
    right: 12,
  },
  addBtn: {
    position: 'absolute',
    right: 28,
    bottom: 64,
    width: 56,
    height: 56,
    borderRadius: 28,
    justifyContent: 'center',
    alignItems: 'center',
  },
  addIcon: {
    width: 36,
    height: 36,
    resizeMode: 'contain',
    // tintColor: 'red',
  },
  listContainer: {
    paddingHorizontal: 12,
  }
});

export default Home;
